import argparse
import socket
from IA_player import*

# Class client
class Communication(object):
    
# Class needs an host name and a nickname to connect itself with the server

    def __init__(self, host, nickname,game):
        self.host=host
        self.nick =nickname
        self.port =8080
        self.con=''
        self.game= game
        #self.ia = IA_player()
                
# This method make a connection with the server, send nickname's player and collects data wich are used by infoCarte 

    def connexion(self):
        
        #help's arguments        
        parser = argparse.ArgumentParser(description='Joueur controle par IA')
        parser.add_argument('--host', help='name of the server', default=self.host)
        parser.add_argument('--port', type=int, help='port of the server', default=8080)
        parser.add_argument('--nick', help='Nickname of the player', default=self.nick)
        args = parser.parse_args()
        #connection server
        print 'Connection au server (%s, %d) ...' % (args.host, args.port)
        self.con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.con.connect((self.host,self.port))
        #receive infos about map
    def receive_first(self):
        data = ''
        print 'receiving turn data ...'
        while not 'end' in data:
            data += self.con.recv(1024)
        print data
        print 'Communication :\n',self.game.infoCarte(data)

        #first data about initializing the game
    def receive(self):
        #data for each turn
        data = ''
        print 'receiving turn data ...'
        while not 'end' in data:
            data += self.con.recv(1024)
        print 'data : ', data
        self.game.Com_map(data)
            
# in case where data start with a end (means game over)

        if data.strip().startswith('end'):
            self.game.finished=True
        
        #send data to the server
        
    def receive_final(self):
        # Receives final data
        
        data = self.con.recv(1024)
        
     
        #data += self.con.recv(1024)
        print data
       

        end_re = r"final\s+(\d)\s+(\d+)"
        m = re.search(end_re, data)
        if m:
            result = int(m.group(1))
        if result:
            print 'Winner !'
        else:
            print 'Looser :\'('
            

    def send (self, choice):
        
            self.con.sendall('\n'.join(choice))
            print '\n'.join(choice),'\n'

                
# main if the method must be run alone.  

if __name__=="__main__":      
    co = Communication('localhost', 'Gary')
    co.client()

